package com.example.servlet.studentServlet;

import com.example.dao.StudentDao;
import com.example.entity.Student;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/addstudent")
public class StudentAddServlet extends HttpServlet {
    private StudentDao studentDao = new StudentDao();


    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 设置请求和响应的字符编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        // 获取表单数据
        String studentId = request.getParameter("studentId");
        String name = request.getParameter("name");
        String grade = request.getParameter("grade");
        String classes = request.getParameter("classes");
        String email = request.getParameter("email");
        System.out.println("==============");
        System.out.println("添加信息：");
        System.out.println(studentId);
        System.out.println(name);
        System.out.println(grade);
        System.out.println(classes);
        System.out.println(email);
        // 创建学生对象
        Student student = new Student(studentId, name, grade, classes, email);
        // 保存到数据库
        boolean b = studentDao.addStudent(student);
        System.out.println(4);
        if (b) {
            System.out.println("添加成功!");
            response.getWriter().write("添加成功！");
            //请求转发
            request.getRequestDispatcher("index.jsp").forward(request, response);
        } else {
            System.out.println("添加失败!");
            response.getWriter().write("添加失败，请稍后重试！");
            response.sendRedirect("addstudent.jsp");
        }

    }
}
